#include "InputHandler.h"
InputHandler::InputHandler()
{
	m_pDIObject = NULL;
	m_pDIKeyboardDevice = NULL;

	if(!InitDirectInput()) 
	{
		MessageBox(TheGame::Instance()->GetWindowHandle(),
			L"Init failed!",
			L"InitDirectInput()",
			MB_OK);
	}
	else if(!InitKeyboard())
	{
		MessageBox(TheGame::Instance()->GetWindowHandle(),
			L"Init failed!",
			L"InitKeyboard()",
			MB_OK);
	}
}
InputHandler::~InputHandler()
{
	if(m_pDIKeyboardDevice != NULL)
	{
		m_pDIKeyboardDevice->Unacquire(); //unacquire device 
		m_pDIKeyboardDevice->Release();   //release keyboard stuff 
		m_pDIKeyboardDevice = NULL;       //pointer to NULL 
	}

	if(m_pDIObject != NULL)
	{
		m_pDIObject->Release(); //release main object
		m_pDIObject = NULL;
	}

}
bool InputHandler::InitDirectInput()
{
	if(FAILED(DirectInput8Create(GetModuleHandle(NULL),
		DIRECTINPUT_VERSION,
		IID_IDirectInput8,
		(void**)&m_pDIObject,
		NULL)))
	{
		MessageBox(TheGame::Instance()->GetWindowHandle(),
			L"DirectInput8Create() failed!",
			L"InitDirectInput()",
			MB_OK);
		return false;
	}

	return true;

}
bool InputHandler::InitKeyboard(void)
{
	if(FAILED(m_pDIObject->CreateDevice(GUID_SysKeyboard,
		&m_pDIKeyboardDevice,
		NULL)))
	{
		MessageBox(TheGame::Instance()->GetWindowHandle(),
			L"CreateDevice() failed!",
			L"InitKeyboard()",
			MB_OK);
		return false;
	}
	if(FAILED(m_pDIKeyboardDevice->SetDataFormat(&c_dfDIKeyboard)))
	{
		MessageBox(TheGame::Instance()->GetWindowHandle(),
			L"SetDataFormat() failed!",
			L"InitKeyboard()",
			MB_OK);
		return false;
	}
	if(FAILED(m_pDIKeyboardDevice->SetCooperativeLevel(TheGame::Instance()->GetWindowHandle(),
		DISCL_BACKGROUND | 
		DISCL_NONEXCLUSIVE)))
	{
		MessageBox(TheGame::Instance()->GetWindowHandle(),
			L"SetCooperativeLevel() failed!",
			L"InitKeyboard()",
			MB_OK);
		return false;
	}
	if(FAILED(m_pDIKeyboardDevice->Acquire()))
	{
		MessageBox(TheGame::Instance()->GetWindowHandle(),
			L"Acquire() failed!",
			L"InitKeyboard()",
			MB_OK);
		return false;
	}

	return true;
} 
bool InputHandler::Update()
{
	if(FAILED(m_pDIKeyboardDevice->GetDeviceState(sizeof(m_KeyBuffer),
		(LPVOID)&m_KeyBuffer)))
	{
		MessageBox(TheGame::Instance()->GetWindowHandle(),
			L"GetDeviceState() failed!",
			L"Update()",
			MB_OK);
		return false;
	}

	return true;
}
bool InputHandler::KeyPressed(int Key)
{
	if(m_KeyBuffer[Key] & 0x80)
	{
		return true;
	}

	return false;
} 
/*bool InputHandler::KeyUp(int Key)
{

}*/